package endpoint

import (
	"context"
	"go-kit-service/pkg/service"

	"github.com/go-kit/kit/endpoint"
)

const (
	UploadSuccess = UploadVideoResponse("upload success")
	UploadFail    = UploadVideoResponse("upload fail")
)

type UploadVideoRequest struct {
	Name string
	Data []byte
}

type UploadVideoResponse string

type Endpoints struct {
	VideoListEndpoint     endpoint.Endpoint
	UploadVideoEndpoint   endpoint.Endpoint
	DownloadVideoEndpoint endpoint.Endpoint
	ConvertVideoEndpoint  endpoint.Endpoint
}

func MakeEndpoints(svr *service.VideoService) Endpoints {
	return Endpoints{
		VideoListEndpoint:     videoListEndpoint(svr),
		UploadVideoEndpoint:   uploadVideoEndpoint(svr),
		DownloadVideoEndpoint: downloadVideoEndpoint(svr),
		ConvertVideoEndpoint:  convertVideoEndpoint(svr),
	}
}

func videoListEndpoint(svr *service.VideoService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		infoList := svr.VideoList()

		return infoList, nil
	}
}

func uploadVideoEndpoint(svr *service.VideoService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		video := request.(UploadVideoRequest)
		if err := svr.UploadVideo(video.Name, video.Data); err != nil {
			return UploadFail, err
		}

		return UploadSuccess, nil
	}
}

func downloadVideoEndpoint(svr *service.VideoService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		name := request.(string)
		videoSrc, err := svr.DownloadVideo(name)
		if err != nil {
			return []byte{}, err
		}

		return videoSrc, nil
	}
}

func convertVideoEndpoint(svr *service.VideoService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		video := request.([]byte)

		return svr.ConvertVideo(video)
	}
}
